package com.hjy.im.server.handler;

import com.hjy.im.message.RpcRequestMessage;
import com.hjy.im.message.RpcResponseMessage;
import com.hjy.im.server.service.UserService;
import com.hjy.im.server.service.UserServiceFactory;
import com.hjy.im.server.service.UserServiceMemoryImpl;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

@ChannelHandler.Sharable
public class RpcRequestMessageHandler  extends SimpleChannelInboundHandler<RpcRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequestMessage rpcRequestMessage) throws Exception {
        RpcResponseMessage rpcresponseMessage = new RpcResponseMessage();
        try{
            System.out.println(rpcRequestMessage);
            //设置返回值类型
            rpcresponseMessage.setSequenceId(rpcRequestMessage.getSequenceId());
            //返回一个实例
            UserService userService = UserServiceFactory.getUserService();
            //通过反射调用方法并获取返回值类型
            Method method = userService.getClass().getMethod(rpcRequestMessage.getMethodName(), rpcRequestMessage.getParameterTypes());

            //获取返回值类型
            Object invoke = method.invoke(userService, rpcRequestMessage.getParameterValue());
            //设置返回值
            rpcresponseMessage.setReturnValue(invoke);

        }catch (Exception e){
            e.printStackTrace();
            rpcresponseMessage.setExceptionValue(e);
        }
        channelHandlerContext.writeAndFlush(rpcresponseMessage);
    }
}
